﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
using Sinacor.Infra.Service.Data;
using Sinacor.Infra.Service.Security.Authorization;
using Sinacor.Infra.Service.Common;

namespace Sinacor.Servico.Bovespa.Titulo.ResourceAccess
{
    public class Mercado : BaseResourceAccess
    {
        #region Construtor

        public Mercado()
            : base(AuthorizationContext.Current.CompanyId)
        {
        }

        #endregion

        #region [PUB] ConsultarMercados
        public List<BusinessEntity.Mercado> ConsultarMercados(BusinessEntity.Parameter.FiltroMercado request)
        {
            List<BusinessEntity.Mercado> response = null;
            StringBuilder sql = new StringBuilder();

            using (DbCommand command = this.DataBase.GetSqlStringCommand(" "))
            {
                #region SQL
                sql.Append(@"SELECT CD_NRMERC AS Codigo, --Código Mercado
                                    CD_ALMERC AS CodigoAlfa, --Código Alfa
                                    DS_MERCADO AS Descricao --Descricao
                             FROM TBOMERCADO ");
                #endregion

                #region Filtro

                if (!string.IsNullOrEmpty(request.CodigoAlfa))
                {
                    sql.Append(" WHERE CD_ALMERC = :CodigoAlfa  ");
                    this.DataBase.AddInParameter(command, "CodigoAlfa", DbType.String, request.CodigoAlfa);
                }

                #endregion

                #region Ordenação

                sql.Append(" ORDER BY CD_NRMERC ");

                #endregion

                command.CommandText = sql.ToString();

                response = this.FindAll<BusinessEntity.Mercado>(command, reader =>
                {
                    BusinessEntity.Mercado item = new BusinessEntity.Mercado();

                    item.Codigo = reader.GetValue<Int32>("Codigo");
                    item.CodigoAlfa = reader["CodigoAlfa"].ToString();
                    item.Descricao = reader["Descricao"].ToString();
                   
                    return item;
                });
            }

            return response;
        }

        #endregion

    }
}
